package cn.alise.util;

import org.apache.log4j.Logger;

import cn.alise.enums.EnumClass;
import cn.alise.exception.ServiceException;

/**
 * 接口请求，返回加解密工具类
 * @author zhuyf
 *
 */
public class HttpSecurityUtil {
	
	public static Logger logger = Logger.getLogger(HttpSecurityUtil.class);
	
	public static SignatureUtil signatureUtil = new SignatureUtil();
	
	public static AesUtil aes = new AesUtil();	
	
	/**
	 * aes加密响应报文
	 * @param retJsonStr
	 * @param appsecret
	 * @return
	 * @throws Exception 
	 * @throws ServiceException
	 */
	public static String encryptReponseJson(String retJsonStr,String appsecret) {
		//加密后的响应报文
		String reponseData = "";
		try {
			reponseData = aes.encrypt(retJsonStr, appsecret.toUpperCase().substring(8, 24));
		} catch(Exception e) {
			logger.error(e);
		}		
		return reponseData;
	}
	
	/**
	 * 验证摘要
	 * @param sJsonParam 请求报文des加密后的字符串
	 * @param lol 待验证的摘要
	 * @throws ServiceException 
	 */
	public static void verifyLol(String sJsonParam,String lol) throws ServiceException {
		//当前摘要
		String curlol = "";
		try {
			curlol = signatureUtil.digest(sJsonParam, "MD5");
			//验证摘要
			if(curlol.equals(sJsonParam)) {
				throw new ServiceException(EnumClass.ResultCodeType.SPARAM_WRONGFUL.getKey(), EnumClass.ResultCodeType.SPARAM_WRONGFUL.getValue());
			}
		} catch(Exception e) {
			throw new ServiceException(EnumClass.ResultCodeType.SPARAM_ERROR.getKey(), EnumClass.ResultCodeType.SPARAM_ERROR.getValue(), e);
		}
	}
	
	/**
	 * 解密请求报文
	 * @param sJsonParam 请求报文des加密后的字符串
	 * @param appsecret 加密key
	 * @return
	 * @throws ServiceException 
	 */
	public static String decryptParam(String sJsonParam,String appsecret) throws ServiceException {
		//解密后的请求报文
		String requestData = "";
		try {
			requestData = aes.decrypt(sJsonParam, appsecret.toUpperCase().substring(8, 24));
		} catch(Exception e) {
			throw new ServiceException(EnumClass.ResultCodeType.JSON_ERROR.getKey(), EnumClass.ResultCodeType.JSON_ERROR.getValue(), e);
		}		
		return requestData;
	}
	
	
}
